package com.wxb.service.impl;

import com.alibaba.nacos.common.utils.AbstractAssert;
import com.wxb.domain.MallSmsLogEntity;
import com.wxb.domain.MallUserEntity;
import com.wxb.domain.MallUserLevelEntity;
import com.wxb.mapper.MallUserLevelMapper;
import com.wxb.mapper.MallUserMapper;
import com.wxb.service.IMallUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Date 2025-05-30 14:30
 * @Version 1.0
 * @Description
 * @ClassName MallUserServiceImpl
 **/
@Service
public class MallUserServiceImpl implements IMallUserService {
    @Autowired
    private MallUserMapper userDao;
    @Autowired
    private MallUserLevelMapper userLevelDao;

    public MallUserEntity queryObject(Long userId) {
        return userDao.queryObject(userId);
    }

    public MallUserEntity queryByOpenId(String openId) {
        return userDao.queryByOpenId(openId);
    }

    public List<MallUserEntity> queryList(Map<String, Object> map) {
        return userDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return userDao.queryTotal(map);
    }

    public void save(String mobile, String password) {
        MallUserEntity user = new MallUserEntity();
        user.setMobile(mobile);
        user.setUsername(mobile);
        user.setPassword(DigestUtils.sha256Hex(password));
        user.setRegisterTime(new Date());
        userDao.save(user);
    }

    public void save(MallUserEntity userVo) {
        userDao.save(userVo);
    }

    public void update(MallUserEntity user) {
        userDao.update(user);
    }

    public void delete(Long userId) {
        userDao.delete(userId);
    }

    public void deleteBatch(Long[] userIds) {
        userDao.deleteBatch(userIds);
    }

    public MallUserEntity queryByMobile(String mobile) {
        return userDao.queryByMobile(mobile);
    }

    public long login(String mobile, String password) throws Exception {
        MallUserEntity user = queryByMobile(mobile);
        AbstractAssert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new Exception("手机号或密码错误");
        }

        return user.getUserId();
    }

    public MallSmsLogEntity querySmsCodeByUserId(Long userId) {
        return userDao.querySmsCodeByUserId(userId);
    }


    public int saveSmsCodeLog(MallSmsLogEntity smsLogVo) {
        return userDao.saveSmsCodeLog(smsLogVo);
    }

    public String getUserLevel(MallUserEntity loginUser) {
        String result = "普通用户";
        MallUserLevelEntity userLevelVo = userLevelDao.queryObject(loginUser.getUserLevelId());
        if (null != userLevelVo) {
            result = userLevelVo.getName();
        }
        return result;
    }
}
